package com.old.nsi_class.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import com.old.common.JSONResult;
import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.DB.JSONResult2;
import com.old.nsi_class.common.properties.Properties;
import com.old.nsi_class.model.*;

@WebServlet("/Class_Course_api")
public class Class_Course_api extends HttpServlet {

	private static final long serialVersionUID = 5593996310509649890L;
	private Gson gson = new Gson();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doPost(req,res);
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    	
		String whereFrom = null;
		whereFrom = req.getParameter("whereFrom");
//		运行耗时
		long startTime = System.currentTimeMillis();

//-------------------------------------------------课程介绍-HTML---------------------------------------------		
		//接受课程介绍html字符串
		if(whereFrom.equals("Course_InsertHtml")) {
			System.out.println("Class_Course_api:WF======Course_InsertHtml");				
			StringBuffer sb = new StringBuffer();
			BufferedReader br = new BufferedReader(
					new InputStreamReader((ServletInputStream)req.getInputStream(), "utf-8") );
			String temp;
			while ((temp = br.readLine()) != null) {
			    sb.append(temp);
			}
			br.close();
			System.out.println(sb.toString());
			Gson gson = new Gson();
		    JsonTransferObject jsonTransferObject = gson.fromJson(sb.toString(), JsonTransferObject.class);//对于javabean直接给出class实例
			
		    System.out.println(jsonTransferObject.getObject01()+jsonTransferObject.getObject02());
			//接受参数
			String Id = jsonTransferObject.getObject01();
			String html01 = jsonTransferObject.getObject02();
			String html02 = jsonTransferObject.getObject03();
			String html03 = jsonTransferObject.getObject04();
			String html04 = jsonTransferObject.getObject05();
			
			System.out.println(html01+html02+html03+html04);
			
			String sql="UPDATE nsi_course SET html01 ='"+html01+"',html02 ='"+html02+"',html03 ='"+html03+"',html04 ='"+html04+"' "
					+ "WHERE Id='"+Id+"';";
			System.out.println("sql:"+sql);
			Course_DB.insert02(sql);
			

			String back="{\"msg\":\"1\"}";
//	    	String Callback = request.getParameter("Callback");//客户端请求参数	  	    	
	    	res.setContentType("text/html;charset=UTF-8");  
//	    	response.getWriter().write(Callback+"("+back+")");	
	    	res.getWriter().write(back);			

	    	
		//返回课程介绍html字符串
		}else if (whereFrom.equals("Course_GetHtml")) {
			System.out.println("Class_Course_api:WF======Course_GetHtml");		
			String Id = req.getParameter("Id");
			String sql="SELECT * from nsi_course WHERE Id="+Id+" ;";
			List<Course_model> list = new ArrayList<Course_model>();
			list=Course_DB.CourseSearch(sql);
	    	Gson gson = new Gson();   	
			String jsonList =gson.toJson(list);
			
			res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write("{\"data\":"+jsonList+"}");
	    	
			
	    	
//-------------------------------------------------课程介绍-文字---------------------------------------------
		
		//返回详细课程介绍-文字
		}else if (whereFrom.equals("Search_Course")) {
			System.out.println("Class_Course_api:WF======Search_Course");		
			String sql=null;
			if (req.getParameter("Id") != null && !req.getParameter("Id").equals("")) {
				String Id = req.getParameter("Id");
				sql="SELECT * from nsi_course Where Id="+Id+" order by CourseRelease DESC;";
			} else if(req.getParameter("CourseSubject") != null && !req.getParameter("CourseSubject").equals("")){
				String CourseSubject = req.getParameter("CourseSubject");
				sql="SELECT * from nsi_course Where CourseSubject='"+CourseSubject+"' order by CourseRelease DESC;";
				System.out.println(sql);
			} else {
				sql="SELECT * from nsi_course order by Id;";
			}
			List<Course_model> list = new ArrayList<Course_model>();	
			list=Course_DB.CourseSearch(sql);
	    	Gson gson = new Gson();   	
			String jsonList =gson.toJson(list);
			res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write("{\"data\":"+jsonList+"}");
	 
		//返回详细课程介绍-文字
		}else if (whereFrom.equals("MyCourse")) {
			System.out.println("Class_Course_api:WF======MyCourse");
			String UserMail = req.getParameter("UserMail");	
			
			String sql="SELECT * FROM nsi_course c,nsi_course_user u where c.Id=u.ClassId and u.UserMail='"+UserMail+"';";
//			查找用户购买的课程
			List<Course_model> list = new ArrayList<Course_model>();	
			list=Course_DB.CourseSearch(sql);
	    	Gson gson = new Gson();   	
			String jsonList =gson.toJson(list);
			res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write("{\"data\":"+jsonList+"}");
	    	
	    	
		//插入详细课程介绍-文字
		}else if (whereFrom.equals("Insert_Course")) {
			System.out.println("Class_Course_api:WF======Insert_Course");		
//			String Id = request.getParameter("Id");
			String ChannelNumber = req.getParameter("ChannelNumber");
			String ChannelName = req.getParameter("ChannelName");
			String Secretkey = req.getParameter("Secretkey");
			String TeacherId = req.getParameter("TeacherId");
			String CourseSubject = req.getParameter("CourseSubject");
			String CourseName = req.getParameter("CourseName");
			String CourseState = req.getParameter("CourseState");
			String CourseDescription = req.getParameter("CourseDescription");
			String ClassBegins = req.getParameter("ClassBegins");
			String CoursePraise = req.getParameter("CoursePraise");
			String CoursePrice = req.getParameter("CoursePrice");
			//String CourseRelease = request.getParameter("CourseRelease");
			String CoursePeople = req.getParameter("CoursePeople");
			String CoverImage = req.getParameter("CoverImage");
			String CourseImage = req.getParameter("CourseImage");

			//当前时间
			java.util.Date currentTime = new java.util.Date(); 
	    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    	String CourseRelease = formatter.format(currentTime);
			
			String sql="REPLACE INTO nsi_course (ChannelNumber,ChannelName,Secretkey,TeacherId,CourseSubject,CourseName,CourseState,CourseDescription,ClassBegins,CoursePraise,CoursePrice,CourseRelease,CoursePeople,CoverImage,CourseImage) "
					+ " values('"+ChannelNumber+"','"+ChannelName+"','"+Secretkey+"','"+TeacherId+"','"+CourseSubject+"','"+CourseName+"','"+CourseState+"','"+CourseDescription+"','"+ClassBegins+"','"+CoursePraise+"','"+CoursePrice+"','"+CourseRelease+"','"+CoursePeople+"','"+CoverImage+"','"+CourseImage+"')";			
			int i=Course_DB.insert02(sql);
			String back="{\"msg\":"+i+"}";  	
	    	res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write(back);
		
		//修改详细课程介绍-文字
		}else if (whereFrom.equals("alter_Course")) {
			System.out.println("Class_Course_api:WF======alter_Course");		
			
			String Id = req.getParameter("Id");
			String ChannelNumber = req.getParameter("ChannelNumber");
			String ChannelName = req.getParameter("ChannelName");
			String Secretkey = req.getParameter("Secretkey");
			String TeacherId = req.getParameter("TeacherId");
			String CourseSubject = req.getParameter("CourseSubject");
			String CourseName = req.getParameter("CourseName");
			String CourseState = req.getParameter("CourseState");
			String CourseDescription = req.getParameter("CourseDescription");
			String ClassBegins = req.getParameter("ClassBegins");
			String CoursePraise = req.getParameter("CoursePraise");
			String CoursePrice = req.getParameter("CoursePrice");
			//String CourseRelease = request.getParameter("CourseRelease");
			String CoursePeople = req.getParameter("CoursePeople");
			
			String CoverImage = req.getParameter("CoverImage");
			String CourseImage = req.getParameter("CourseImage");

			//当前时间
				java.util.Date currentTime = new java.util.Date(); 
		    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    	String CourseRelease = formatter.format(currentTime);
			
			String sql="UPDATE nsi_course SET "
					+ "ChannelNumber='"+ChannelNumber+"',"
					+ "ChannelName='"+ChannelName+"',"
					+ "Secretkey='"+Secretkey+"',"
					+ "TeacherId='"+TeacherId+"',"
					+ "CourseSubject='"+CourseSubject+"',"
					+ "CourseName='"+CourseName+"',"
					+ "CourseState='"+CourseState+"',"
					+ "CourseDescription='"+CourseDescription+"',"
					+ "ClassBegins='"+ClassBegins+"',"
					+ "CoursePraise='"+CoursePraise+"',"
					+ "CoursePrice='"+CoursePrice+"',"
//					+ "CourseRelease='"+CourseRelease+"',"
					+ "CoursePeople='"+CoursePeople+"',"
					+ "CoverImage='"+CoverImage+"',"
					+ "ChannelNumber='"+ChannelNumber+"',"
					+ "CourseImage='"+CourseImage+"' "
					+ "WHERE Id ='"+Id+"';";
					
			int i=Course_DB.insert02(sql);
			String back="{\"msg\":"+i+"}";  	
	    	res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write(back);	
	    	
		//后台-删除：课程介绍-文字
		}else if (whereFrom.equals("Delete_Course")) {
			System.out.println("Class_Course_api:WF======Delete_Course");		
			String Id = req.getParameter("Id");
			String sql="DELETE FROM nsi_course WHERE Id ='"+Id+"';";    	
			int i=Course_DB.CourseDelete(sql);			//成功：1,失败 -2
			String back="{\"msg\":\""+i+"\"}";
		    res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write(""+back+"");
	    	
		//后台-返回详细课程介绍-文字
		}else if (whereFrom.equals("Admin_Search_Course")) {
			System.out.println("Class_Course_api:WF======Admin_Search_Course");		
//			String Id = request.getParameter("Id");
			String sql="SELECT * from nsi_course order by CourseRelease DESC;";
			List<Course_model> list = new ArrayList<Course_model>();	
			list=Course_DB.CourseSearch(sql);
	    	Gson gson = new Gson();
			String jsonList =gson.toJson(list);
			int i=Course_DB.count(sql);			
			res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write("{\"code\":0,\"msg\":\"\",\"count\":"+i+",\"data\":"+jsonList+"}");	
			
//		 	System.out.println("{\"data\":"+jsonList+"}");
//			response.setContentType("application/json;charset=UTF-8");  
//	    	response.getWriter().write("{\"data\":"+jsonList+"}");
//	    	response.getWriter().write("{\"data\":\"aaaa\"}");
		
//-------------------------------------------------课程介绍----------------------------------------------
		
	    	
    	/**
    	 * 直播配置
    	 */
		}else if("stickyInformation".equals(whereFrom)) {
			System.out.println("Class_Course_api:WF======stickyInformation");
			String TeacherId= req.getParameter("TeacherId");
			String CourseId = req.getParameter("CourseId");
			String sqlTeacher ="SELECT * FROM nsi_teacher WHERE Id='"+TeacherId+"';";
			int count = Course_DB.count(sqlTeacher);
			String sqlCourse = "SELECT * FROM nsi_course WHERE Id='"+CourseId+"'; ";
			int count2 = Course_DB.count(sqlCourse);
			if(count>0) {
				if(count2>0) {
					String sql = "UPDATE nsi_properties SET teacherId='"+TeacherId+"',courseId='"+CourseId+"' WHERE id='1';";
					Properties.commonMethod(sql);
					JSONResult2 jr = new JSONResult2();
					String data = gson.toJson(jr);
					//返回结果集
					JSONResult2.toResult(req, res, data);
				}else {
					String message = "课程Id参数不合法";
					JSONResult2 jr = new JSONResult2(message);
					String data = gson.toJson(jr);
					JSONResult2.toResult(req, res, data);
				}
			}else {
				String message = "教师Id参数不合法";
				JSONResult2 jr = new JSONResult2(message);
				String data = gson.toJson(jr);
				JSONResult2.toResult(req, res, data);
			}


		/**
		 * 显示功能	
		 */
		}else if("showInformation".equals(whereFrom)) {
	    	List<Properties_model> list = Properties.searchProperties();
	    	String TeacherId = list.get(0).getTeacherId();
	    	String CourseId = list.get(0).getCourseId();
			String sqlTeacher = "SELECT * FROM nsi_teacher WHERE Id='"+TeacherId+"';";
			List<Teacher_model> listT = Course_DB.searchTeacher(sqlTeacher);
			String sqlCourse = "SELECT * FROM nsi_course WHERE Id='"+CourseId+"';";
			List<Course_model> listC = Course_DB.CourseSearch(sqlCourse);

			JSONResult jr = new JSONResult(listC,listT);
			String data = gson.toJson(jr);
			//返回结果集
			JSONResult2.toResult(req, res, data);	

			/**
	     * 查看一次课程购买人	
	     */
		}else if("AdminSearch_Course_User".equals(whereFrom)) {
			System.out.println("Class_Course_api:WF=====AdminSearch_Course_User");
			
			String UserMail = req.getParameter("UserMail") != null && !req.getParameter("UserMail").equals("") ? req.getParameter("UserMail") : "0";			
			String ClassId = req.getParameter("ClassId") != null && !req.getParameter("ClassId").equals("") ? req.getParameter("ClassId") : "0";			
			
//			分页参数 ：第几页、每页几个。默认值：1、20；
			Integer pageNum = req.getParameter("pageNum") != null && !req.getParameter("pageNum").equals("") ? Integer.parseInt(req.getParameter("pageNum")) : 1;
			Integer OnePageNum = req.getParameter("OnePageNum") != null && !req.getParameter("OnePageNum").equals("") ? Integer.parseInt(req.getParameter("OnePageNum")) : 20;
			int pageNumX=(pageNum-1)*OnePageNum;
			
			String sql,sqlcount=null;
//			只搜课程
			if (UserMail.equals("0")&&ClassId!="0") {
				sql = "SELECT * FROM nsi_course_user WHERE ClassId='"+ClassId+"' limit "+pageNumX+","+OnePageNum+";";
				sqlcount = "SELECT * FROM nsi_course_user WHERE ClassId='"+ClassId+"';";	
//			只搜用户
			} else if(ClassId.equals("0")&&UserMail!="0") {
				sql = "SELECT * FROM nsi_course_user WHERE UserMail='"+UserMail+"' limit "+pageNumX+","+OnePageNum+";";
				sqlcount = "SELECT * FROM nsi_course_user WHERE UserMail='"+UserMail+"';";
//			空搜索
			}else if(ClassId.equals("0")&&UserMail.equals("0")) {
				sql = "SELECT * FROM nsi_course_user  limit "+pageNumX+","+OnePageNum+";";
				sqlcount = "SELECT * FROM nsi_course_user;";
//			两项限定搜索
			}else {
				sql = "SELECT * FROM nsi_course_user WHERE ClassId='"+ClassId+"' and UserMail='"+UserMail+"' limit "+pageNumX+","+OnePageNum+";";
				sqlcount = "SELECT * FROM nsi_course_user WHERE ClassId='"+ClassId+"' and UserMail='"+UserMail+"';";
			}
			List<Course_User_model> list = new ArrayList<Course_User_model>();
			list=Course_DB.CourseUserSearch(sql);
			int count = Course_DB.count(sqlcount);			
			String jsonList =gson.toJson(list);
		    res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write("{\"code\":0,\"msg\":\"\",\"count\":"+count+",\"data\":"+jsonList+"}");	
	    	

		}else {
			//结果集-3
			JSONResult2.toResultFault(req, res);
		}
		
//		运行耗时计算
		long endTime = System.currentTimeMillis();    //获取结束时间
	    System.out.println("-------Class_Course_api程序耗时："+whereFrom+":"+ (endTime-startTime) + "ms");	    
    }
    
//-------------------------------------------------置顶功能----------------------------------------------    
    public static void main(String[] args) {

	}

}
